<script lang="ts" setup>
import { NScrollbar, NButton, NIcon, NCard, NDataTable, NEmpty, NDropdown } from 'naive-ui'
import { Settings20Regular } from '@vicons/fluent'
import { Bug, Plus } from '@vicons/tabler'
import { Codemirror } from 'vue-codemirror'
import { json } from '@codemirror/lang-json'
import { computed, h, ref, watch } from 'vue'
import ToolAuthModal from '@/views/LLMStudio/tools/components/ToolAuthModal.vue'
import CircleIcons from '@/components/CircleIcons.vue'

const extensions = [json()]
const showAuthModal = ref(false)
const schemaJson = ref('')
const exampleSchema = `{
  "openapi": "3.1.0",
  "info": {
    "title": "Get weather data",
    "description": "Retrieves current weather data for a location.",
    "version": "v1.0.0"
  },
  "servers": [
    {
      "url": "https://weather.example.com"
    }
  ],
  "paths": {
    "/location": {
      "get": {
        "description": "Get temperature for a specific location",
        "operationId": "GetCurrentWeather",
        "parameters": [
          {
            "name": "location",
            "in": "query",
            "description": "The city and state to retrieve the weather for",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "deprecated": false,
        "responses": {
          "200": {
            "description": "Success",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "temperature": {
                      "type": "number",
                      "description": "The temperature in Celsius"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {}
  }
}`
const initSchema = `{
  "openapi": "3.1.0",
  "info": {
    "title": "Untitled",
    "description": "Your OpenAPI specification",
    "version": "v1.0.0"
  },
  "servers": [
    {
      "url": "This Is Your Server Base Url"
    }
  ],
  "paths": {
    // Add your OpenAPI paths here
  },
    "components": {
    "schemas": {}
  }
}`

const popselectOptions = [
  {
    label: '查询天气',
    key: 'getWeather'
  },
  {
    label: '基础',
    key: 'base'
  }
]

const onSelect = (key: string) => {
  if (key === 'getWeather') {
    schemaJson.value = exampleSchema
  }
  if (key === 'base') {
    schemaJson.value = initSchema
  }
}

const openAuthModal = () => {
  showAuthModal.value = true
}

const submitAuth = (authData: any) => {
  console.log('Auth Data:', authData)
  showAuthModal.value = false
}

// Schema 解析结果
const parsedSchema = computed(() => {
  if (!schemaJson.value || schemaJson.value.trim() === '') {
    return { name: '', baseUrl: '', paths: [] }
  }

  try {
    const schemaObj = JSON.parse(schemaJson.value)
    const paths = []

    if (schemaObj.paths) {
      for (const [path, methods] of Object.entries(schemaObj.paths)) {
        for (const [method, details] of Object.entries(methods as Record<string, any>)) {
          const parameters = details.parameters || []
          const responses = details.responses || {}

          paths.push({
            name: details.operationId || `${method.toUpperCase()} ${path}`,
            description: details.description || '',
            method: method.toUpperCase(),
            path: path,
            parameters: parameters,
            responses: responses
          })
        }
      }
    }

    return {
      name: schemaObj.info?.title || '',
      description: schemaObj.info?.description || '',
      version: schemaObj.info?.version || '',
      baseUrl: schemaObj.servers?.[0]?.url || '',
      paths: paths
    }
  } catch (error) {
    console.error('Error parsing schema:', error)
    return { name: '', baseUrl: '', paths: [] }
  }
})

watch(
  () => schemaJson,
  (newValue) => {
    console.log('Schema updated:', newValue)
  }
)

// 对外公开,供父组件调用 获取解析结果
const getParsedSchema = () => parsedSchema

// 暴露方法给父组件
defineExpose({ getParsedSchema })

// 表格列定义
const paramColumns = [
  { title: '参数名', key: 'name' },
  { title: '位置', key: 'in' },
  { title: '类型', key: 'type' },
  { title: '说明', key: 'description' },
  {
    title: '必填',
    key: 'required',
    render: (row: any) => {
      return row.required
        ? h(CircleIcons, { type: 'check', size: 16 }, { default: () => 'Yes' })
        : h(CircleIcons, { type: 'cross', size: 16 }, { default: () => 'No' })
    },
    align: 'center'
  }
]

const responseColumns = [
  { title: '参数名', key: 'name' },
  { title: '类型', key: 'type' },
  { title: '说明', key: 'description' },
  {
    title: '必返回',
    key: 'required',
    render: (row: any) => {
      return row.required
        ? h(CircleIcons, { type: 'check', size: 16 }, { default: () => 'Yes' })
        : h(CircleIcons, { type: 'cross', size: 16 }, { default: () => 'No' })
    },
    align: 'center'
  }
]

// 获取参数数据
const getParametersData = (parameters) => {
  return parameters.map((param) => ({
    name: param.name,
    in: param.in,
    type: param.schema?.type || param.type || 'unknown',
    description: param.description || '',
    required: param.required
  }))
}

/**
 * 获取响应数据
 * @param responses API 响应对象
 * @returns 处理后的响应数据数组
 */
const getResponsesData = (responses: Record<string, any>) => {
  if (!responses || Object.keys(responses).length === 0) {
    return [
      {
        status: 200,
        description: 'OK',
        contentType: 'unknown',
        fields: []
      }
    ]
  }
  return Object.entries(responses).map(([status, details]: [string, any]) => {
    const contentType = Object.keys(details.content || {})[0] || 'unknown'
    const schema = details.content?.[contentType]?.schema || {}
    const properties = schema.properties || {}

    const fields = Object.entries(properties).map(([name, prop]: [string, any]) => ({
      name,
      type: prop.type,
      description: prop.description || '',
      required: schema.required?.includes(name) || false
    }))

    return {
      status: parseInt(status),
      description: details.description || '',
      contentType,
      fields
    }
  })
}
</script>

<template>
  <div class="w-full h-full flex justify-between gap-5">
    <n-card title="Schema 编辑器" style="width: 50%; height: 100%" class="rounded-xl">
      <Codemirror
        class="h-full bg-gray-100 rounded-xl"
        v-model="schemaJson"
        :style="{ height: 'calc(100vh - 370px)' }"
        :autofocus="true"
        :indent-with-tab="true"
        :tab-size="2"
        :extensions="extensions"
      />
      <template #header-extra>
        <n-dropdown trigger="click" :options="popselectOptions" @select="onSelect">
          <n-button type="default" size="small">
            <template #icon>
              <n-icon size="20">
                <Plus />
              </n-icon>
            </template>
            添加例子
          </n-button>
        </n-dropdown>
      </template>
    </n-card>
    <n-card title="解析结果" style="width: 50%; height: 100%" class="rounded-xl">
      <n-scrollbar class="h-full" content-style="height: calc(100vh - 370px);">
        <div
          v-if="parsedSchema.paths.length === 0"
          class="w-full h-600px flex justify-center items-center"
        >
          <n-empty description="暂无数据"></n-empty>
        </div>
        <template v-else>
          <h3>API 名称: {{ parsedSchema.name }}</h3>
          <p class="mb-4">Base URL: {{ parsedSchema.baseUrl }}</p>
          <n-card
            v-for="path in parsedSchema.paths"
            :key="path.name"
            :title="path.name"
            class="mb-4 rounded-xl cursor-pointer hover:bg-gray-100"
            size="small"
            :bordered="false"
          >
            <p>请求方式: {{ path.method }}</p>
            <p>请求路径: {{ path.path }}</p>
            <h4 class="my-3">入参:</h4>
            <n-data-table
              :columns="paramColumns"
              :data="getParametersData(path.parameters)"
              :bordered="false"
            />
            <h4 class="my-3">响应:</h4>
            <n-card
              class="rounded-xl"
              v-for="response in getResponsesData(path.responses)"
              :key="response.status"
              :title="`状态码: ${response.status} | 描述: ${response.description}`"
            >
              <n-data-table :columns="responseColumns" :data="response.fields" :bordered="false" />
            </n-card>

            <template #header-extra>
              <n-button type="default" size="small">
                <template #icon>
                  <n-icon size="20">
                    <Bug />
                  </n-icon>
                </template>
                调试
              </n-button>
            </template>
          </n-card>
        </template>
      </n-scrollbar>
      <template #header-extra>
        <n-button type="default" size="small" @click="openAuthModal">
          <template #icon>
            <n-icon size="20">
              <Settings20Regular />
            </n-icon>
          </template>
          接口权限
        </n-button>
      </template>
    </n-card>
  </div>
  <ToolAuthModal v-model:show="showAuthModal" @submit="submitAuth"></ToolAuthModal>
</template>
